import React, { PureComponent } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Tree, message, Input, Radio } from 'antd';
import TableForm from './TableForm';
import { connect } from 'dva';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { ContentPackage, InputC, SelectC, PrimaryC, TableC, PrimaryGhostC, DATA_ENTRY, SecondHeaderC, AdvancedSearch, ModalC, TenantC } from '../../../comps';
import ModalInst from './Modal';
import { isZiGuanEvir } from '../../../utils/commonFunc';
import { formSelectData } from '../../../utils/utils';

const { TreeNode } = Tree;

const { TextArea } = Input;
moment.locale('zh-cn');
const FormItem = Form.Item;

@connect(({ roleModel, userM: user, globalM }) => ({
  roleModel,
  user,
  globalM,
}))
@Form.create()
export default class Station extends PureComponent {
  state = {
    titleModal: '新增角色',
    saveVisible: false,
    formItem: {},
    checkedKeys2: [],
    dataList2: [],
    dataList: [],
    expandedKeys: [],
    autoExpandParent: true,
    checkedKeys: [],
    selectedKeys: [],
    TreeList: [],
    treeTable: [],
    zhxzSelect: null,
    superMan: localStorage.getItem('antd-pro-superMan'),
    currentPage: 1,
    numInPage: 10,
    editRoleId: undefined, // 编辑时的角色id
    isZiGuan: false, // 是否是资管环境
    sysData: [], // 子系统下拉
    isReset: false, // 是否点击了重置
    userModalVisible: false, // 关联用户模态框显示隐藏
    userSelectData: undefined, // 选中的关联用户下拉数据
    userTableData: undefined, // 关联用户表格数据
    userSelectDataCompare: undefined, // 保存关联用户变更前的数据
    searchObj: {}, // 查询条件
  };

  // 页面初始函数
  UNSAFE_componentWillMount = () => {
    // 判断是否是资管环境
    if (isZiGuanEvir() == false) {
      this.setState({
        isZiGuan: false,
      });
    } else {
      this.setState({
        isZiGuan: true,
      });

      const {
        globalM: {
          dataDictionary: { sysno = [] },
        },
      } = this.props;
      // 获取子系统下拉枚举
      this.setState({
        sysData: formSelectData(sysno),
      });
    }

    this.props.dispatch({
      type: 'roleModel/Search',
      payload: {},
      callback: () => {},
    });
    this.props.dispatch({
      type: 'roleModel/SearchMenu',
      payload: {},
    });
    if (localStorage.getItem('antd-pro-superMan') == 'true') {
      this.props.dispatch({
        type: 'roleModel/SearchTenant',
        payload: {},
      });
    }
  };

  searchById = (e) => {
    this.setState(
      {
        currentPage: 1,
        numInPage: 10,
        isReset: false,
      },
      () => {
        if (e.roleName != undefined) {
          e.roleName = e.roleName.trim();
          const values = {
            roleName: e.roleName,
          };
          this.setState(
            {
              searchObj: values,
            },
            () => {
              this.props.dispatch({
                type: 'roleModel/save',
                payload: { loading: true },
              });
              this.props.dispatch({
                type: 'roleModel/Search',
                payload: this.state.searchObj,
                callback: () => {},
              });
            },
          );
        } else {
          this.setState(
            {
              searchObj: {},
            },
            () => {
              this.props.dispatch({
                type: 'roleModel/save',
                payload: { loading: true },
              });
              this.props.dispatch({
                type: 'roleModel/Search',
                payload: this.state.searchObj,
                callback: () => {},
              });
            },
          );
        }
      },
    );
  };

  changeReset = (current, pagesize) => {
    const { isReset } = this.state;
    if (isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      this.setState({
        isReset: false,
      });
      return;
    }
    this.setState({
      currentPage: current,
      numInPage: pagesize,
    });
  };

  // 新增角色按钮点击
  handleTableSave = () => {
    this.props.dispatch({
      type: 'roleModel/SearchUser',
      payload: {},
    });

    const { form } = this.props;
    form.resetFields(['descriptionfrom', 'roleIdFrom', 'roleNameFrom', 'createdBy', 'sysno']);
    this.setState(
      {
        titleModal: '新增角色',
        saveVisible: true,
        formItem: {},
        dataList: [],
        expandedKeys: [],
        autoExpandParent: true,
        checkedKeys: [],
        halfCheckedKeys: [],
        selectedKeys: [],
        TreeList: [],
        checkedKeys2: [],
        dataList2: [],
        treeTable: [],
      },
      () => {
        const {
          roleModel: { TreeChildren },
        } = this.props;
        this.handleMerge(TreeChildren);
      },
    );
  };

  // 初始化数据的逻辑
  handleMerge = (data) => {
    const { dataList } = this.state;
    data.map((item) => {
      if (item.menuModels && item.menuModels.length > 0) {
        this.handleMerge(item.menuModels);
      } else {
        const num = _.findIndex(dataList, function (o) {
          return o.id == item.id;
        });

        dataList &&
          dataList.splice(num >= 0 ? num : dataList.length, num >= 0 ? 1 : 0, {
            id: item.id,
            operateType: 'view', // item.operateType
          });
        this.setState({ dataList });
      }
    });
  };

  // 展开/收起节点时触发
  onExpand = (expandedKeys) => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };

  // 点击复选框触发
  onCheck = (checkedKeys, e) => {
    this.setState({
      checkedKeys,
      halfCheckedKeys: e.halfCheckedKeys,
    });
  };

  // 点击树节点触发
  onSelect = (selectedKeys, info) => {
    this.setState({ selectedKeys });
  };

  // 生成树形结构dom
  renderTreeNodes = (data) => {
    const { dataList } = this.state;
    return data.map((item) => {
      const num = _.findIndex(dataList, function (o) {
        return o.id == item.id;
      });
      // 警告问题出处 **********************************************************
      const onChange = (e) => {
        item.operateType = e.target.value;
        dataList &&
          dataList.splice(num >= 0 ? num : dataList.length, num >= 0 ? 1 : 0, {
            id: item.id,
            operateType: e.target.value,
          });
        this.setState({ dataList });
      };
      if (item.menuModels && item.menuModels.length > 0) {
        return (
          <TreeNode title={item.name} key={item.id} dataRef={item}>
            {this.renderTreeNodes(item.menuModels)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          title={
            <span>
              {item.name}
              <Radio.Group style={{ marginLeft: '8px' }} onChange={onChange} value={item.operateType || 'view'}>
                <Radio value={'view'}>查看</Radio>
                <Radio value={'edit'}>修改</Radio>
              </Radio.Group>
            </span>
          }
          key={item.id}
        />
      );
    });
  };

  // 发送数据
  handleSubmit = (e) => {
    const treessss = [];
    const {
      roleModel: { TreeChildren },
    } = this.props;
    e ? e.preventDefault() : '';
    const { checkedKeys, dataList } = this.state;
    const data = dataList.filter((item) => {
      return checkedKeys.some((val) => val == item.id);
    });
    data.map((item) => {
      this.treeTable(item, TreeChildren, treessss);
    });
    this.setState({
      TreeList: data,
      treeTable: treessss,
    });
    return data;
  };

  treeTable = (item, treeChildren, treessss) => {
    treeChildren.map((item2) => {
      if (item2.menuModels && item2.menuModels.length > 0) {
        this.treeTable(item, item2.menuModels, treessss);
      } else if (item.id == item2.id) {
        item2.operateType = item.operateType;
        treessss.push(item2);
      }
    });
  };

  // 关联用户按钮点击事件
  relatedUserClick = () => {
    const tempArr = [];
    this.state.userTableData &&
      this.state.userTableData.forEach((item) => {
        tempArr.push(item.id);
      });
    setTimeout(() => {
      this.props.form.setFieldsValue({
        relatedUser: tempArr,
      });
    }, 0);
    this.setState({
      userSelectDataCompare: tempArr,
      userModalVisible: true,
    });
  };

  // 关联用户模态框内容渲染
  userModal = () => {
    const {
      roleModel: { userData },
    } = this.props;
    return (
      <div>
        <Form>
          <SelectC
            dataIndex='relatedUser'
            form={this.props.form}
            title='关联用户'
            showSearch={true}
            allowClear={true}
            isMultiple={true}
            maxTagCount={0}
            initialValue={this.state.userSelectData || undefined}
            filterOption={(
              input,
              option, // 模糊搜索value 和 title
            ) => {
              return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 || option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
            }}
            dataSource={userData}
            optionTitle={true}
            positionBody={true}
          />
        </Form>
      </div>
    );
  };

  // 关联用户模态框ok事件
  userOk = () => {
    const {
      roleModel: { userOriginData },
    } = this.props;
    const tempSelect = this.props.form.getFieldValue('relatedUser');
    const tempTable = [];
    // 用选中的关联用户select数据遍历处理出关联用户table数据
    if (tempSelect && tempSelect.length > 0) {
      tempSelect &&
        tempSelect.forEach((itemSelect) => {
          userOriginData &&
            userOriginData.forEach((item) => {
              if (item.id == itemSelect) {
                tempTable.push({ id: item.id, name: item.name, userAccount: item.userAccount });
              }
            });
        });
    }

    this.setState({
      userSelectData: tempSelect,
      userTableData: tempTable,
      userModalVisible: false,
    });
  };

  // 关联用户模态框cancel事件
  userCancel = () => {
    this.setState({
      userSelectData: this.state.userSelectDataCompare,
      userModalVisible: false,
    });
  };

  render() {
    const { form } = this.props;
    const { getFieldDecorator } = this.props.form;
    const {
      roleModel: { data, TreeChildren },
    } = this.props;
    const that = this;
    const table = {
      data,
      //  删除
      onDeleteFrom(item) {
        that.props.dispatch({
          type: 'roleModel/deleteRole',
          payload: item,
          callback: (type) => {
            if (type == 'success') {
              that.props.dispatch({
                type: 'roleModel/Search',
                payload: that.state.searchObj,
                callback: () => {},
              });
            }
          },
        });
      },
      // 编辑点击事件
      onEditFrom(item) {
        // 处理关联用户下拉数据
        const tempArr = [];
        item.userModels &&
          item.userModels.map((item) => {
            tempArr.push(item.id);
          });

        that.props.dispatch({
          type: 'roleModel/SearchUser',
          payload: {},
        });
        that.setState({
          userSelectData: tempArr,
          userTableData: item.userModels || undefined,
        });
        form.resetFields(['descriptionfrom', 'roleIdFrom', 'roleNameFrom', 'createdBy', 'sysno']);

        that.props.dispatch({
          type: 'roleModel/SearchMenu2',
          payload: item,
        });
        const menuSelect = [];
        // 2021-03-27 by zxy
        // 根据角色ID，获取角色的菜单
        /* 在点击“编辑”时调用该接口，用户初始化菜单选项，本来在列表中已获取该数据，但因数据量过大，
            看不到返回结构，后端无法定位一些问题（初始进来，菜单初始化有问题，精确查询后，无为题）
            因而前端打个补丁，在编辑前再获取一次数据。
        */
        that.props.dispatch({
          type: 'roleModel/getMenuByRoleId',
          payload: {
            id: item.id,
            sysno: that.state.isZiGuan ? item.sysno : undefined,
          },
          callback: (args) => {
            args &&
              args.forEach((ele1) => {
                if (ele1.menuModels) {
                  ele1.menuModels.forEach((ele2) => {
                    if (ele2.menuModels && Array.isArray(ele2.menuModels)) {
                      ele2.menuModels.forEach((ele3) => {
                        menuSelect.push(ele3.id);
                      });
                    } else {
                      menuSelect.push(ele2.id);
                    }
                  });
                } else {
                  menuSelect.push(ele1.id);
                }
              });

            that.setState(
              {
                treeTable: item.menuModels ? item.menuModels : [],
                titleModal: '修改角色',
                saveVisible: true,
                formItem: item,
                checkedKeys: menuSelect,
                checkedKeys2: menuSelect,
                zhxzSelect: item.createdBy,
              },
              () => {
                const {
                  roleModel: { TreeChildren },
                } = that.props;
                that.handleMerge(TreeChildren);
              },
            );
          },
        });
      },
    };
    const userColumns = [
      {
        title: '用户名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '用户账号',
        dataIndex: 'userAccount',
        key: 'userAccount',
      },
    ];

    const modal = {
      titleModal: that.state.titleModal,
      saveVisible: that.state.saveVisible,
      // 关联菜单信息
      menuTable() {
        return (
          <div>
            <SecondHeaderC style={{ marginBottom: '10px' }} title='关联菜单信息' />
            <Tree
              checkable={true}
              onExpand={that.onExpand}
              expandedKeys={that.state.expandedKeys}
              autoExpandParent={that.state.autoExpandParent}
              onCheck={that.onCheck}
              checkedKeys={that.state.checkedKeys}
              onSelect={that.onSelect}
              selectedKeys={that.state.selectedKeys}
            >
              {that.renderTreeNodes(TreeChildren)}
            </Tree>
          </div>
        );
      },
      // 关联用户信息
      userTable() {
        return (
          <div>
            <SecondHeaderC style={{ marginBottom: '10px' }} title='关联用户信息' Right={<PrimaryGhostC title='关联用户' onClick={that.relatedUserClick} />} />
            <div style={{ marginTop: '10px' }}>
              <TableC columns={userColumns} scroll={{ y: 180 }} hidePage={true} rowKey={'id'} dataSource={that.state.userTableData} />
            </div>
          </div>
        );
      },
      // 角色基本信息
      saveModal() {
        const formItemLayout = {
          labelCol: {
            span: 8,
          },
        };
        return (
          <Form labelCol={{ span: 4 }} style={{ marginLeft: -50 }}>
            <Row style={{ marginBottom: '10px' }}>
              <Col span={12}>
                <InputC
                  form={that.props.form} // form对象
                  dataIndex={'roleIdFrom'}
                  title={'角色代码'}
                  formItemLayout={formItemLayout}
                  rules={[{ required: true, max: 100, message: '请输入角色代码' }]}
                  initialValue={that.state.formItem.roleId || undefined}
                  disabled={that.state.titleModal == '修改角色'}
                />
              </Col>
              <Col span={12}>
                <InputC
                  form={that.props.form} // form对象
                  dataIndex={'roleNameFrom'}
                  title={'角色名称'}
                  formItemLayout={formItemLayout}
                  initialValue={that.state.formItem.roleName}
                  rules={[{ required: true, max: 100, message: '请输入角色名称' }]}
                />
              </Col>
            </Row>
            <Row>
              <Col span={24}>
                {that.state.superMan == 'true' ? (
                  <TenantC
                    title='租户选择'
                    form={that.props.form}
                    dataIndex='createdBy'
                    disabled={that.state.titleModal == '修改角色'}
                    initialValue={that.state.formItem.createdBy}
                    showSearch={true}
                    formItemLayout={formItemLayout}
                    optionTitle={true}
                  />
                ) : null}
              </Col>
              {that.state.isZiGuan ? (
                <Col span={24}>
                  <SelectC
                    title='子系统'
                    dataIndex='sysno'
                    form={that.props.form}
                    initialValue={
                      that.state.titleModal == '修改角色' ? (that.state.formItem.sysno && that.state.formItem.sysno != null ? that.state.formItem.sysno : undefined) : undefined
                    }
                    formItemLayout={formItemLayout}
                    dataSource={that.state.sysData}
                    allowClear={true}
                  />
                </Col>
              ) : undefined}
            </Row>
            <Row style={{ marginBottom: '10px' }}>
              <Col
                // span={24}
                style={{
                  marginTop: '10px',
                }}
              >
                <FormItem label='描述'>
                  {getFieldDecorator('descriptionfrom', { initialValue: that.state.formItem.description })(<TextArea style={{ minHeight: 32 }} placeholder='请输入' rows={4} />)}
                </FormItem>
              </Col>
            </Row>
          </Form>
        );
      },

      // 新增编辑模态框确认事件
      confirmRevise(e) {
        e.preventDefault();
        const treeData = that.handleSubmit();
        that.setState({
          checkedKeys2: that.state.checkedKeys,
          dataList2: that.state.dataList,
        });
        const {
          user: { currentUser },
        } = that.props;
        const { form } = that.props;
        const { userSelectData } = that.state;
        // 关联用户数据处理后传给后端
        const tempUserData = [];
        userSelectData &&
          userSelectData.map((item) => {
            tempUserData.push({ id: item });
          });
        form.validateFields(['createdBy', 'roleNameFrom', 'roleIdFrom', 'descriptionfrom', 'sysno'], (err, fieldsValue) => {
          if (err) return;
          if (that.state.titleModal == '新增角色') {
            // 新增
            const values = {
              roleId: fieldsValue.roleIdFrom || undefined,
              roleName: fieldsValue.roleNameFrom,
              description: fieldsValue.descriptionfrom,
              userModels: tempUserData, // 关联用户
              menuModels: treeData,
              createdBy: fieldsValue.createdBy,
            };
            if (that.state.isZiGuan && fieldsValue.sysno) {
              values.sysno = fieldsValue.sysno;
            }
            that.props.dispatch({
              type: 'roleModel/save',
              payload: { loading: true },
            });
            that.props.dispatch({
              type: 'roleModel/saveTable',
              payload: values,
              callback: (type) => {
                if (type == 'success') {
                  that.setState({
                    saveVisible: false,
                    currentPage: 1,
                    userSelectData: [],
                    userTableData: [],
                  });
                  that.props.dispatch({
                    type: 'roleModel/Search',
                    payload: that.state.searchObj,
                    callback: () => {},
                  });
                }
              },
            });
          } else {
            // 编辑
            const values = {
              id: that.state.formItem.id,
              roleName: fieldsValue.roleNameFrom,
              roleId: fieldsValue.roleIdFrom || undefined,
              createdBy: that.state.formItem.createdBy,
              createdTs: that.state.formItem.createdTs,
              description: fieldsValue.descriptionfrom,
              lastUpdBy: currentUser.name,
              userModels: tempUserData, // 关联用户
              menuModels: treeData,
            };
            if (that.state.isZiGuan && fieldsValue.sysno) {
              values.sysno = fieldsValue.sysno;
            }
            that.props.dispatch({
              type: 'roleModel/save',
              payload: { loading: true },
            });
            that.props.dispatch({
              type: 'roleModel/saveTable',
              payload: values,
              callback: (type) => {
                if (type == 'success') {
                  that.setState({
                    saveVisible: false,
                    currentPage: 1,
                    userSelectData: [],
                    userTableData: [],
                  });
                  that.props.dispatch({
                    type: 'roleModel/Search',
                    payload: that.state.searchObj,
                    callback: () => {},
                  });
                }
              },
            });
          }
        });
      },

      cancel() {
        that.setState({
          saveVisible: false,
          zhxzSelect: '',
          userSelectData: [],
          userTableData: [],
        });
      },
    };

    const searchProps = {
      dataSource: [
        {
          dataIndex: 'roleName',
          title: '角色',
          type: DATA_ENTRY.INPUT,
          allowClear: true,
        },
      ],
      // 点击查询按钮
      onQuery: (e) => {
        this.searchById(e);
      },
      onClear: () => {
        // 点击重置按钮
        this.setState({
          isReset: true,
          searchObj: {},
        });
      },
    };

    return (
      <ContentPackage
        title='角色配置'
        contentHtml={
          <div>
            <div>
              <AdvancedSearch {...searchProps} />
              <PrimaryC title='新增' style={{ margin: '10px' }} onClick={this.handleTableSave} />
              <TableForm {...table} changeReset={this.changeReset} currentPage={this.state.currentPage} numInPage={this.state.numInPage} />
            </div>

            <ModalInst {...modal} />
            <ModalC title={'关联用户'} visible={this.state.userModalVisible} onOk={this.userOk} onCancel={this.userCancel} width={450}>
              {this.userModal()}
            </ModalC>
          </div>
        }
      />
    );
  }
}
